import React from 'react';
import { Spin } from 'antd';
import { isEqual, isEmpty } from 'lodash';
import {WeaErrorPage, WeaLocaleProvider, WeaTools} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const { ls } = WeaTools;
import Title from './Title';
import { setContentviewHeight} from '../../util/common';
//内容组件
class EContent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tabdata: props.edata.data,
            currentTab: props.edata.currenttab,
            refresh: false,
        }
        this.handleTabData = this.handleTabData.bind(this);
    }
    componentWillReceiveProps(nextProps){
        if(!isEqual(nextProps, this.props)){
            this.setState({
                tabdata: nextProps.edata.data,
                currentTab: nextProps.edata.currenttab,
                refresh: false,
            }); 
        }
    }

    shouldComponentUpdate(nextProps, nextState){
        return !isEqual(this.state, nextState) || !isEqual(this.props, nextProps)
    }
    componentDidMount(){
        this.props.onRef(this);
    }
    handleTabData(tabid){
        const { params } = this.props.config;
        const { currentTab } = this.state;
        this.setState({
            refresh: tabid === currentTab,
            currentTab: tabid,
        });
        WeaTools.callApi('/api/portal/element/rankinglisttab', 'POST', {...params, tabid}).then(result => {
            if(tabid === this.state.currentTab){
              if (result.moreUrl) {
                  $(`#more_${params.eid}`).parent().css({display: 'block'});
                  window.elements_more_params[params.eid] = {moreurl: result.moreUrl};
              } else {
                  $(`#more_${params.eid}`).parent().css({display: 'none'});
              }  
              this.setState({
                  tabdata: result,
                  refresh: false,
              });   
            }
       });
    }
    filterData = (data) => {
        // 删除全是空的行
        const deleteNullRows = (data) => {
            const _data = [];
            for (let i1 = 0, len1 = data.length; i1 < len1; i1++) {
                const v1 = data[i1];
                let isNullRow = true;
                for (let i2 = 0, len2 = v1.length; i2 < len2; i2++) {
                    if (v1[i2]) {
                        isNullRow = false;
                        break;
                    }
                }
                if (!isNullRow) {
                    _data.push(v1);
                }
            }
            return _data;
        };
        
        if (data.length > 0) {
            data = deleteNullRows(data); // 删除空行
            if (data.length > 0) {
                data = data[0].map((col, i) => data.map((row) => row[i])); // 列转行
                data = deleteNullRows(data); // 删除空列
                data = data[0].map((col, i) => data.map((row) => row[i])); // 还原
            }
        }
        
        return data;
    };
    render() {
        const { config, edata, handleRefresh, handleDelete, fontSizeMp } = this.props;
        const { tabdata, currentTab, refresh } = this.state;
        const { tabids, titles, esetting } = edata;
        const { eid } = config.params;
        let { fontStyle,header } = config.item;
        if(!isEmpty(fontSizeMp)) fontStyle = fontSizeMp;
        esetting.fontStyle = fontStyle;
        const { contentview = {} } = config.item;
        let cstyle = {height: contentview.style.height,overflow: "auto"};
        if(header.displayPosition && header.displayPosition == 'bottom'){
            if(tabids && tabids.length > 1 || tabids && tabids.length == 1 && esetting.isAlwaysShow=='1'){
                if(contentview.style.height){
                  if(esetting.tabstyle == '1' && esetting.tabvalue){
                    cstyle = setContentviewHeight(contentview.style.height,esetting.tabvalue)
                  }else{
                      cstyle = {height: parseInt(contentview.style.height)-32+"px",overflow: "auto"};
                  } 
                }else {
                    cstyle = {height: contentview.style.height,overflow: "auto"};
                }
                let elementH=parseInt(contentview.style.height)-parseInt($(`#titleContainer_${eid}`).css('height'));
                if(elementH!=parseInt(cstyle.height)){
                    if(elementH<parseInt(cstyle.height)){
                        cstyle.height=elementH+"px";
                    }
                }
            }
        }

        let { styleType, data } = tabdata;
        if (data && typeof data == 'string') {
          // 手动录入的数据
          try {
            data = this.filterData(JSON.parse(data));
          } catch (e) {}
        } else if (data && typeof data == 'object') {
          // 自定义SQL查询的数据
          data = this.filterData(data);
        } else {
          data = [];
        }
        const headdata = data[0] || []; // 第一行作为标题行
        const bodydata = data.slice(1); // 第二行开始作为数据行
        const top3data = bodydata.slice(0, 3); // 排名前3的数据
        const otherdata = bodydata.slice(3); // 排名第4开始的数据
        let contentHtml = (
          <div className="ranking-list-no-data">
            <i className="icon-coms-blank" style={{fontSize: 60}} />
            <div>{getLabel(83553, '暂无数据')}</div>
          </div>
        );
        if (bodydata.length > 0) {
          const colWidth = 100 / (headdata.length + 1) + '%';
          const colgroup = (
            <colgroup>
              <col width={colWidth} />
              {headdata.map((item, index) => (
                <col key={index} width={colWidth} />
              ))}
            </colgroup>
          );
          const thead = (
            <table class="ranking-list-table-head">
              {colgroup}
              <thead>
                <tr>
                  <th></th>
                  {headdata.map((item, index) => (
                    <th key={index}>{item}</th>
                  ))}
                </tr>
              </thead>
            </table>
          );
          const tbody = (
            <table className="ranking-list-table-body">
              {colgroup}
              <tbody>
                {otherdata.map((item, index) => (
                  <tr key={index}>
                    <td>{index + 4}</td>
                    {item.map((item, index) => (
                      <td key={index}>{item}</td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          );

          if (styleType == '1') {
            const tbodytop3 = top3data.map((item, index) => {
              let style = {};
              if (index == 0) {
                style = { border: '1px solid #ffc601', color: '#d7892c' };
              } else if (index == 1) {
                style = { border: '1px solid #9fd7ff', color: '#40a7ff' };
              } else if (index == 2) {
                style = { border: '1px solid #e6aa99', color: '#d0916d' };
              }
              return (
                <table key={index} className="ranking-list-style1-table" style={style}>
                  {colgroup}
                  <tbody>
                    <tr>
                      <td>
                        <img src={`/spa/portal/images/rankinglist/s01-${index + 1}.png`} alt="" />
                      </td>
                      {item.map((item, index) => (
                        <td key={index}>{item}</td>
                      ))}
                    </tr>
                  </tbody>
                </table>
              );
            });

            contentHtml = (
              <div className="ranking-list-data">
                {thead}
                {tbodytop3}
                {tbody}
              </div>
            );
          } else if (styleType == '2') {
            const tbodytop3 = (
              <div className="ranking-list-style2">
                <div className="ranking-list-style2-info" style={{ position: 'relative', top: 20, paddingBottom: 20, width: '30%', border: '2px solid #d1d1d1', color: '#d6d6d6' }}>
                  <img src={`/spa/portal/images/rankinglist/s02-2.png`} alt="" width="auto" height="auto" />
                  <ul>{top3data[1] ? top3data[1].map((item, index) => <li key={index}>{item}</li>) : <li>{getLabel(83553, '暂无数据')}</li>}</ul>
                  <div style={{ position: 'absolute', bottom: 18, width: '100%', height: 2, backgroundColor: '#d1d1d1' }}></div>
                </div>
                <div className="ranking-list-style2-info" style={{ width: '1%' }}></div>
                <div className="ranking-list-style2-info" style={{ width: '38%', border: '2px solid #dcad03', color: '#dcad03' }}>
                  <img src={`/spa/portal/images/rankinglist/s02-1.png`} alt="" width="auto" height="auto" />
                  <ul>{top3data[0] ? top3data[0].map((item, index) => <li key={index}>{item}</li>) : <li>{getLabel(83553, '暂无数据')}</li>}</ul>
                </div>
                <div className="ranking-list-style2-info" style={{ width: '1%' }}></div>
                <div className="ranking-list-style2-info" style={{ position: 'relative', top: 40, paddingBottom: 40, width: '30%', border: '2px solid #c2998d', color: '#934731' }}>
                  <img src={`/spa/portal/images/rankinglist/s02-3.png`} alt="" width="auto" height="auto" />
                  <ul>{top3data[2] ? top3data[2].map((item, index) => <li key={index}>{item}</li>) : <li>{getLabel(83553, '暂无数据')}</li>}</ul>
                  <div style={{ position: 'absolute', bottom: 38, width: '100%', height: 2, backgroundColor: '#c2998d' }}></div>
                </div>
              </div>
            );

            contentHtml = (
              <div className="ranking-list-data">
                {tbodytop3}
                {otherdata.length > 0 ? thead : null}
                {otherdata.length > 0 ? tbody : null}
              </div>
            );
          } else if (styleType == '3') {
            const tbodytop3 = (
              <div className="ranking-list-style3">
                <div className="ranking-list-style3-info" style={{ width: '30%', color: '#ababab' }}>
                  <img src={`/spa/portal/images/rankinglist/s03-2.png`} alt="" width="auto" height="auto" />
                  <ul>{top3data[1] ? top3data[1].map((item, index) => <li key={index}>{item}</li>) : <li>{getLabel(83553, '暂无数据')}</li>}</ul>
                </div>
                <div className="ranking-list-style3-info" style={{ width: '40%', marginTop: -30, color: '#f55a00' }}>
                  <img src={`/spa/portal/images/rankinglist/s03-1.png`} alt="" width="auto" height="auto" />
                  <ul>{top3data[0] ? top3data[0].map((item, index) => <li key={index}>{item}</li>) : <li>{getLabel(83553, '暂无数据')}</li>}</ul>
                </div>
                <div className="ranking-list-style3-info" style={{ width: '30%', color: '#d0916d' }}>
                  <img src={`/spa/portal/images/rankinglist/s03-3.png`} alt="" width="auto" height="auto" />
                  <ul>{top3data[2] ? top3data[2].map((item, index) => <li key={index}>{item}</li>) : <li>{getLabel(83553, '暂无数据')}</li>}</ul>
                </div>
              </div>
            );

            contentHtml = (
              <div className="ranking-list-data">
                {tbodytop3}
                {otherdata.length > 0 ? thead : null}
                {otherdata.length > 0 ? tbody : null}
              </div>
            );
          } else if (styleType == '4') {
            contentHtml = (
              <div className="ranking-list-data">
                {thead}
                <table className="ranking-list-table-body ranking-list-style4-table">
                  {colgroup}
                  <tbody>
                    {top3data.map((item, index) => {
                      let style = {};
                      if (index == 0) {
                        style = { color: '#fe9227' };
                      } else if (index == 1) {
                        style = { color: '#92abbe' };
                      } else if (index == 2) {
                        style = { color: '#d0916d' };
                      }
                      return (
                        <tr key={index} style={style}>
                          <td>
                            <img src={`/spa/portal/images/rankinglist/s04-${index + 1}.png`} alt="" />
                          </td>
                          {item.map((item, index) => (
                            <td key={index}>{item}</td>
                          ))}
                        </tr>
                      );
                    })}
                    {otherdata.map((item, index) => (
                      <tr key={index}>
                        <td>
                          <span>{index + 4}</span>
                        </td>
                        {item.map((item, index) => (
                          <td key={index}>{item}</td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            );
          }
        }
        const _titleProps = {
            currentTab,
            config,
            titles,
            tabids,
            handleRefresh,
            handleDelete,
            fontSizeMp,
            tabwidth: esetting.tabwidth,
            methodvalue: esetting.methodvalue,
            isAlwaysShow: esetting.isAlwaysShow,
            tabstyle: esetting.tabstyle,
            tabvalue: esetting.tabvalue,
            handleTabData: this.handleTabData
        }

        return <div>
            <Title ecId={`${this && this.props && this.props.ecId || ''}_Title@ehenrp`} {..._titleProps}/>
            <div className="tabContant" id={`tabcontant_${eid}`} style={cstyle}>
                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@ymw1h1`} spinning={refresh}>{contentHtml}</Spin>
            </div>
         </div>;
    }
}

class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
            return ( <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@44ehu9`} msg = { hasErrorMsg ? this.props.error : getLabel(385218,"对不起，该页面异常，请联系管理员！") }/>
        );
    }
}
EContent = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(EContent);
export default EContent;